/**
 * Created by ZhaoJinBing on 2017/8/9.
 */
define(['jquery'], function ($) {
    var sortArr = [];

    var getDirectChildren = function (target, parentId) {
        var childrenRows = $(target).treegrid('getChildren', parentId);
        var tempRows = new Array();
        $.each(childrenRows, function (index, item) {
            if (item._parentId != parentId) {
                return true;
            }
            tempRows.push(item);
        });
        return tempRows;
    };

    var init = function (targetRow, sourceRow, point) {
        var targetRowParentId = targetRow._parentId;
        var sourceRowParentId = sourceRow._parentId;
        if (sourceRowParentId != targetRowParentId) {
            return false;
        }
        if (point == 'append') {
            return false;
        }
        return true;
    };

    var set = function (target, sourceRow) {
        var sourceRowPosition = -1;
        var sourceRowParentId = sourceRow._parentId;
        var childrenRows = getDirectChildren(target, sourceRowParentId);

        $.each(childrenRows, function (index, item) {
            if (item.id == sourceRow.id) {
                sourceRowPosition = index;
                return false;
            }
        });

        var preRow = null;
        var nextRow = null;
        if (sourceRowPosition > 0) {
            preRow = childrenRows[sourceRowPosition - 1];
        }
        if (sourceRowPosition < childrenRows.length) {
            nextRow = childrenRows[sourceRowPosition + 1];
        }

        var obj = {};
        obj.id = sourceRow.id;
        if (preRow == null) {
            obj.next = nextRow.id;
        } else if (nextRow == null) {
            obj.pre = preRow.id;
        } else {
            obj.pre = preRow.id;
            obj.next = nextRow.id;
        }

        var removeIndex = -1;
        $.each(sortArr, function (index, item) {
            if (item.id == obj.id) {
                removeIndex = index;
                return false;
            }
        });
        if (removeIndex > -1) {
            sortArr.splice(removeIndex, 1, obj);
        } else {
            sortArr.push(obj);
        }
    };

    var reset = function () {
        sortArr = [];
    };

    var get = function () {
        return sortArr;
    };

    return {
        init: init,
        set: set,
        get: get,
        reset: reset
    }
});
